<template>
  <view class="wrap">
    <u-collapse :head-style="headStyle" v-if="roleId === 3">
      <u-collapse-item
        :title="'比赛信息'"
        v-for="(item, index) in list"
        :key="index"
      >
        <u-cell-item title="比赛情况ID" :value="item.id"></u-cell-item>
        <u-cell-item title="开始时间" :value="item.createTime"></u-cell-item>
        <u-cell-item title="结束时间" :value="item.endTime"></u-cell-item>
        <u-cell-item
          title="比赛结果"
          :value="!item.result ? '结果暂无' : item.result"
        ></u-cell-item>
        <u-cell-item title="场地" :value="item.space.name"></u-cell-item>
        <u-cell-item title="球队1" :value="item.team1.name"></u-cell-item>
        <u-cell-item title="球队2" :value="item.team2.name"></u-cell-item>
        <view class="remark">
          <text>备注</text>
          <view>{{ item.remark }}</view>
        </view>
        <view>
          <view class="btn">
            <u-button
              type="primary"
              shape="circle"
              plain
              @click="showDeleteAllMatches(item.id)"
              >删除比赛信息</u-button
            >
          </view>
        </view>
      </u-collapse-item>
    </u-collapse>
    <u-collapse :head-style="headStyle" v-if="roleId === 1 || roleId === 2">
      <u-collapse-item
        :title="'比赛信息'"
        v-for="(item, index) in list"
        :key="index"
      >
        <u-cell-item title="比赛情况ID" :value="item.id"></u-cell-item>
        <u-cell-item title="开始时间" :value="item.createTime"></u-cell-item>
        <u-cell-item title="结束时间" :value="item.endTime"></u-cell-item>
        <u-cell-item
          title="比赛结果"
          :value="!item.result ? '结果暂无' : item.result"
        ></u-cell-item>
        <u-cell-item title="场地" :value="item.space.name"></u-cell-item>
        <u-cell-item title="球队1" :value="item.team1.name"></u-cell-item>
        <u-cell-item title="球队2" :value="item.team2.name"></u-cell-item>
        <view>
          <view class="btn">
            <u-button
              type="warning"
              shape="circle"
              plain
              @click="showUpdateMatch(item)"
              v-if="roleId === 2"
              >修改</u-button
            >
          </view>
          <view class="btn">
            <u-button
              type="primary"
              shape="circle"
              plain
              @click="showAddResult(item)"
              v-if="roleId === 2 && !item.result"
              >确认比赛结果</u-button
            >
          </view>
          <view class="btn">
            <u-button
              type="success"
              shape="circle"
              plain
              @click="showAddPlayer(item.id)"
              v-if="roleId === 2"
              >记录球员表现</u-button
            >
          </view>
        </view>
      </u-collapse-item>
    </u-collapse>
    <view class="btn">
      <u-button type="success" @click="showAddMatch" v-if="roleId === 2">
        添加比赛
      </u-button>
    </view>
    <!-- 添加比赛信息 -->
    <u-popup
      v-model="addMatchShow"
      mode="bottom"
      border-radius="10"
      closeable
      height="600"
    >
      <view class="addMatchForm">
        <u-form
          :model="addMatchForm"
          ref="addMatchFormRef"
          :error-type="['message']"
        >
          <u-notice-bar mode="horizontal" :list="recommendList"></u-notice-bar>
          <u-form-item label="开始时间" prop="createTime" label-width="150rpx">
            <u-picker
              v-model="showCreateTime"
              mode="time"
              :params="params"
              @confirm="selectCreateTime"
            ></u-picker>
            <view
              @click="showCreateTime = true"
              style="
                height: 80rpx;
                width: 400rpx;
                border-bottom: 2rpx solid #82848a;
              "
              >{{ addMatchForm.createTime }}</view
            >
          </u-form-item>
          <u-form-item label="结束时间" prop="endTime" label-width="150rpx">
            <u-picker
              v-model="showEndTime"
              mode="time"
              :params="params"
              @confirm="selectEndTime"
            ></u-picker>
            <view
              @click="showEndTime = true"
              style="
                height: 80rpx;
                width: 400rpx;
                border-bottom: 2rpx solid #82848a;
              "
              >{{ addMatchForm.endTime }}</view
            >
          </u-form-item>
          <u-form-item label="场地" label-width="150rpx">
            <u-select
              v-model="showSpace"
              :list="spaceList"
              @confirm="selectSpace"
            ></u-select>
            <view
              @click="showSpace = true"
              style="
                height: 80rpx;
                width: 400rpx;
                border-bottom: 2rpx solid #82848a;
              "
              >{{ selectedSpace }}</view
            >
          </u-form-item>
          <u-form-item label="对战球队" label-width="150rpx">
            <u-select
              v-model="showTeam"
              :list="teamList"
              @confirm="selectTeam"
            ></u-select>
            <view
              @click="showTeam = true"
              style="
                height: 80rpx;
                width: 400rpx;
                border-bottom: 2rpx solid #82848a;
              "
              >{{ selectedTeam }}</view
            >
          </u-form-item>
          <u-form-item label="备注" label-width="150rpx">
            <u-input v-model="addMatchForm.remark"></u-input>
          </u-form-item>
          <u-button
            type="primary"
            shape="circle"
            :ripple="true"
            @click="addMatch"
            >提交</u-button
          >
        </u-form>
      </view>
    </u-popup>
    <!-- 修改比赛信息 -->
    <u-popup
      v-model="updateMatchShow"
      mode="bottom"
      border-radius="10"
      closeable
      height="600"
    >
      <view class="updateMatchForm">
        <u-form
          :model="updateMatchForm"
          ref="updateMatchFormRef"
          :error-type="['message']"
        >
          <u-form-item label="开始时间" label-width="150rpx">
            <u-picker
              v-model="showCreateTime"
              mode="time"
              :params="params"
              @confirm="updateCreateTime"
            ></u-picker>
            <view
              @click="showCreateTime = true"
              style="
                height: 80rpx;
                width: 400rpx;
                border-bottom: 2rpx solid #82848a;
              "
              >{{ updateMatchForm.createTime }}</view
            >
          </u-form-item>
          <u-form-item label="结束时间" prop="endTime" label-width="150rpx">
            <u-picker
              v-model="showEndTime"
              mode="time"
              :params="params"
              @confirm="updateEndTime"
            ></u-picker>
            <view
              @click="showEndTime = true"
              style="
                height: 80rpx;
                width: 400rpx;
                border-bottom: 2rpx solid #82848a;
              "
              >{{ updateMatchForm.endTime }}</view
            >
          </u-form-item>
          <u-form-item label="场地" label-width="150rpx">
            <u-select
              v-model="showSpace"
              :list="spaceList"
              @confirm="selectSpace"
            ></u-select>
            <view
              @click="showSpace = true"
              style="
                height: 80rpx;
                width: 400rpx;
                border-bottom: 2rpx solid #82848a;
              "
              >{{ selectedSpace }}</view
            >
          </u-form-item>
          <u-form-item label="对战球队" label-width="150rpx">
            <u-select
              v-model="showTeam"
              :list="teamList"
              @confirm="selectTeam"
            ></u-select>
            <view
              @click="showTeam = true"
              style="
                height: 80rpx;
                width: 400rpx;
                border-bottom: 2rpx solid #82848a;
              "
              >{{ selectedTeam }}</view
            >
          </u-form-item>
          <u-form-item label="备注" label-width="150rpx">
            <u-input v-model="updateMatchForm.remark"></u-input>
          </u-form-item>
          <u-button
            type="primary"
            shape="circle"
            :ripple="true"
            @click="updateMatch"
            >提交</u-button
          >
        </u-form>
      </view>
    </u-popup>
    <!-- 填写修改结果 -->
    <u-popup v-model="addResultShow" mode="bottom" border-radius="10" closeable>
      <view class="addResult">
        <u-row>
          <u-col span="4"> {{ team1.name }}得分 </u-col>
          <u-col span="7">
            <u-input type="number" v-model="res1" border height="50"></u-input>
          </u-col>
        </u-row>
        <view style="height: 30rpx"></view>
        <u-row>
          <u-col span="4"> {{ team2.name }}得分 </u-col>
          <u-col span="7">
            <u-input type="number" v-model="res2" border height="50"></u-input>
          </u-col>
        </u-row>
        <view class="btn">
          <u-button
            type="primary"
            shape="circle"
            :ripple="true"
            @click="addResult"
            >提交</u-button
          >
        </view>
      </view>
    </u-popup>
    <!-- 填写球员表现 -->
    <u-popup
      v-model="addPlayerShow"
      mode="bottom"
      border-radius="10"
      closeable
      height="600"
    >
      <view class="addPlayerForm">
        <u-form
          :model="addPlayerForm"
          ref="addPlayerFormRef"
          :error-type="['message']"
        >
          <u-form-item label="球员" label-width="150rpx">
            <u-select
              v-model="showPlayer"
              :list="playerList"
              @confirm="selectPlayer"
            ></u-select>
            <view
              @click="showPlayer = true"
              style="
                height: 80rpx;
                width: 400rpx;
                border-bottom: 2rpx solid #82848a;
              "
              >{{ selectedPlayer }}</view
            >
          </u-form-item>
          <u-form-item label="比赛进球数" label-width="150rpx">
            <u-number-box
              v-model="addPlayerForm.matchGoals"
              max="20"
            ></u-number-box>
          </u-form-item>
          <u-form-item label="比赛助攻数" label-width="150rpx">
            <u-number-box
              v-model="addPlayerForm.matchAssist"
              max="20"
            ></u-number-box>
          </u-form-item>
          <u-form-item label="比赛抢断数" label-width="150rpx">
            <u-number-box
              v-model="addPlayerForm.matchSteal"
              max="20"
            ></u-number-box>
          </u-form-item>
          <u-form-item label="比赛失误数" label-width="150rpx">
            <u-number-box
              v-model="addPlayerForm.matchMistake"
              max="20"
            ></u-number-box>
          </u-form-item>
          <u-form-item label="比赛犯规数" label-width="150rpx">
            <u-number-box
              v-model="addPlayerForm.matchFoul"
              max="20"
            ></u-number-box>
          </u-form-item>
          <u-button
            type="primary"
            shape="circle"
            :ripple="true"
            @click="addPlayer"
            >提交</u-button
          >
        </u-form>
      </view>
    </u-popup>
    <!-- 删除比赛信息 -->
    <u-popup v-model="deleteMatchShow" mode="top">
      <view>
        <text>是否删除？</text>
        <view class="btn">
          <u-button type="primary" plain @click="deleteMatch">是</u-button>
        </view>
        <view class="btn">
          <u-button type="error" plain @click="deleteMatchShow = false"
            >否</u-button
          >
        </view>
      </view>
    </u-popup>
    <u-toast ref="matchToastRef" />
    <!-- 加载更多 -->
    <u-loadmore :status="status" @loadmore="load" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentPage: 1,
      size: 10,
      total: -1,
      roleId: -1,
      tid: -1,
      cid: -1,
      sid: -1,
      matchId: -1,
      headStyle: {
        fontWeight: "800",
        fontSize: "30rpx",
        height: "100rpx",
      },
      list: [],
      spaceList: [],
      teamList: [],
      playerList: [],
      addMatchForm: {
        cid: "",
        createTime: "",
        endTime: "",
        remark: "",
        team1: {
          id: "",
        },
        team2: {
          id: "",
        },
        space: {
          id: "",
        },
      },
      addMatchFormRule: {
        createTime: [
          { required: true, message: "开始时间不能为空", trigger: true },
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: true },
        ],
      },
      updateMatchForm: {
        id: "",
        createTime: "",
        endTime: "",
        remark: "",
        team1: {
          id: "",
        },
        team2: {
          id: "",
        },
        space: {
          id: "",
        },
      },
      // 控制时间选择器需要哪些参数
      params: {
        year: true,
        month: true,
        day: true,
        hour: true,
        minute: true,
        second: true,
      },
      showCreateTime: false,
      // 显示选择结束时间
      showEndTime: false,
      showSpace: false,
      showTeam: false,
      showPlayer: "",
      selectedSpace: "",
      selectedTeam: "",
      addMatchShow: false,
      updateMatchShow: false,
      deleteMatchShow: false,
      addResultShow: false,
      addPlayerShow: false,
      team1: "",
      team2: "",
      res1: "",
      res2: "",
      result: "",
      addPlayerForm: {
        id: "",
        trainGoals: 0,
        trainAssist: 0,
        trainSteal: 0,
        trainMistake: 0,
        trainFoul: 0,
        matchGoals: 0,
        matchAssist: 0,
        matchSteal: 0,
        matchMistake: 0,
        matchFoul: 0,
      },
      selectedPlayer: "",
      spaceIds: [],
      // 保存推荐场地名称
      recommendList: [],
    };
  },
  methods: {
    // 首先获取到用户所在球队信息
    async getCurrentTeam() {
      const { data } = await this.$request({
        url: "/team/currentTeam",
        data: {
          rid: this.roleId,
        },
      });
      if (data.code !== 500 && data) {
        this.tid = data.id;
        this.addMatchForm.team1.id = data.id;
        this.updateMatchForm.team1.id = data.id;
        data.playerinfos.forEach((item) => {
          let obj = {};
          obj.label = item.name;
          obj.value = item.id;
          this.playerList.push(obj);
        });
      }
      this.getCurrentMatches(this.currentPage, this.size);
    },

    // 获取当前用户所有比赛信息
    async getCurrentMatches(currentPage, size) {
      const { data } = await this.$request({
        url: "/match/currentMatch",
        data: {
          currentPage,
          size,
          tid: this.tid,
        },
      });
      this.total = data.total;
      if (this.total === 0) {
        this.status = "nomore";
      }
      let len = this.list.length;
      if (len < this.total) {
        data.data.forEach((item) => {
          this.list.push(item);
        });
        if (this.list.length === this.total) {
          this.status = "nomore";
        }
      }
    },

    // 获取所有比赛信息
    async getAllMatches(currentPage, size) {
      const { data } = await this.$request({
        url: "/match/",
        data: {
          currentPage,
          size,
        },
      });
      this.total = data.total;
      if (this.total === 0) {
        this.status = "nomore";
      }
      let len = this.list.length;
      if (len < this.total) {
        data.data.forEach((item) => {
          this.list.push(item);
        });
        if (this.list.length === this.total) {
          this.status = "nomore";
        }
      }
    },

    // 获取所有场地信息
    async getAllSpaces() {
      const { data } = await this.$request({
        url: "/space/selectedSpace",
      });
      data.object.forEach((item) => {
        let obj = {};
        obj.label = item.name;
        obj.value = item.id;
        this.spaceList.push(obj);
      });
    },

    // 获取球队信息
    async getAllTeams() {
      const { data } = await this.$request({
        url: "/team/getTeam",
        data: {
          tid: this.tid,
        },
      });
      data.object.forEach((item) => {
        let obj = {};
        obj.label = item.name;
        obj.value = item.id;
        this.teamList.push(obj);
      });
    },

    // 获取当前教练信息
    async getCurrentCoach() {
      const { data } = await this.$request({
        url: "/coachinfo/currentCoach",
      });
      this.addMatchForm.cid = data.id;
      this.cid = data.id;
    },

    // 选择对战球队
    selectTeam(e) {
      this.addMatchForm.team2.id = e[0].value;
      this.selectedTeam = e[0].label;
    },

    // 选择开始时间
    selectCreateTime(e) {
      this.addMatchForm.createTime = `${e.year}-${e.month}-${e.day} ${e.hour}:${e.minute}:${e.second}`;
    },

    // 选择结束时间
    selectEndTime(e) {
      this.addMatchForm.endTime = `${e.year}-${e.month}-${e.day} ${e.hour}:${e.minute}:${e.second}`;
    },

    // 选择开始时间
    updateCreateTime(e) {
      this.updateMatchForm.createTime = `${e.year}-${e.month}-${e.day} ${e.hour}:${e.minute}:${e.second}`;
    },

    // 选择结束时间
    updateEndTime(e) {
      this.updateMatchForm.endTime = `${e.year}-${e.month}-${e.day} ${e.hour}:${e.minute}:${e.second}`;
    },

    // 选择场地
    selectSpace(e) {
      this.addMatchForm.space.id = e[0].value;
      this.updateMatchForm.space.id = e[0].value;
      this.selectedSpace = e[0].label;
    },

    // 显示添加比赛
    showAddMatch() {
      this.addMatchShow = true;
      this.getRecommendSpace();
    },

        // 控制场地表中容纳球队数量-1或者+1
    async updateSpaceTeamNum(sid,num) {
      const {data} = await this.$request({
        url: '/space/teamNum',
        method: 'put',
        contentType: 'application/x-www-form-urlencoded',
        data: {
          sid,
          num
        }
      })
    },

    // 添加比赛
    addMatch() {
      this.getRecommendSpace();
      this.$refs.addMatchFormRef.validate(async (valid) => {
        if (valid) {
          const { data } = await this.$request({
            url: "/match/",
            method: "post",
            data: this.addMatchForm,
          });
          if (data.code === 200) {
            this.addMatchShow = false;
            this.updateSpaceTeamNum(this.addMatchForm.space.id, -1);
            return this.$refs.matchToastRef.show({
              title: data.message,
              type: "success",
            });
          } else {
            return this.$refs.matchToastRef.show({
              title: data.message,
              type: "error",
            });
          }
        } else {
          return this.$refs.matchToastRef.show({
            title: "输入不合法，请重新输入！",
            type: "error",
          });
        }
      });
    },

    // 获取推荐信息
    async getRecommendSpace() {
      const { data } = await this.$request({
        url: "/recommend/",
        data: {
          cid: this.cid,
        },
      });
      this.spaceIds = data.object;
      this.getSpaceByRecommend();
    },

    // 根据推荐获取场地信息
    async getSpaceByRecommend() {
      const { data } = await this.$request({
        url: "/space/spaceById",
        method: "post",
        data: this.spaceIds,
      });
      data.object.forEach((item) => {
        if (this.recommendList.length === 0) {
          // 当数组为空，拼接字符串
          this.recommendList.push("系统推荐选择场地: " + item.name);
        } else {
          this.recommendList.push(item.name);
        }
      });
    },

    // 显示修改比赛信息
    showUpdateMatch(item) {
      this.updateMatchShow = true;
      this.updateMatchForm.id = item.id;
      this.updateMatchForm.createTime = item.createTime;
      this.updateMatchForm.endTime = item.endTime;
      this.updateMatchForm.team1.id = item.team1.id;
      this.updateMatchForm.team2.id = item.team2.id;
      this.updateMatchForm.space.id = item.space.id;
      this.updateMatchForm.remark = item.remark;
      this.selectedSpace = item.space.name;
      this.selectedTeam = item.team2.name;
    },

    // 修改比赛
    async updateMatch() {
      const { data } = await this.$request({
        url: "/match/",
        method: "put",
        data: this.updateMatchForm,
      });
      if (data.code === 200) {
        this.updateMatchShow = false;
        return uni.reLaunch({
          url: "/pages/match/index",
        });
      } else {
        return this.$refs.matchToastRef.show({
          title: data.message,
          type: "error",
        });
      }
    },

    // 显示添加结果
    showAddResult(item) {
      this.addResultShow = true;
      this.sid = item.space.id;
      this.matchId = item.id;
      this.team1 = item.team1;
      this.team2 = item.team2;
    },

    // 添加比赛结果
    async addResult() {
      if (!this.res1 || !this.res2) {
        return this.$refs.matchToastRef.show({
          title: "得分不能为空！",
          type: "error",
        });
      } else if (this.res1 < 0 || this.res2 < 0) {
        return this.$refs.matchToastRef.show({
          title: "得分不能为负！",
          type: "error",
        });
      } else {
        this.result = this.res1 + " : " + this.res2;
        const { data } = await this.$request({
          url: "/match/addResult",
          method: "post",
          contentType: "application/x-www-form-urlencoded",
          data: {
            id: this.matchId,
            result: this.result,
          },
        });
        if (data.code === 200) {
          this.addResultShow = false;
          this.winTeam(this.res1, this.res2);
          this.updateSpaceTeamNum(this.sid, +1);
          return uni.reLaunch({
            url: "/pages/match/index",
          });
        } else {
          return this.$refs.matchToastRef.show({
            title: data.message,
            type: "error",
          });
        }
      }
    },

    // 判断两个球队中哪个球队获胜
    async winTeam(res1, res2) {
      if (res1 > res2) {
        // 球队1获胜
        await this.$request({
          url: "/team/winNum",
          method: "post",
          contentType: "application/x-www-form-urlencoded",
          data: {
            tid: this.team1.id,
          },
        });
      } else if (res1 < res2) {
        // 球队2获胜
        await this.$request({
          url: "/team/winNum",
          method: "post",
          contentType: "application/x-www-form-urlencoded",
          data: {
            tid: this.team2.id,
          },
        });
      }
    },

    // 选择球员
    selectPlayer(e) {
      this.addPlayerForm.id = e[0].value;
      this.selectedPlayer = e[0].label;
    },

    // 显示添加球员基本信息
    showAddPlayer(id) {
      this.addPlayerShow = true;
      this.addPlayerForm.id = id;
    },

    // 添加球员表现
    async addPlayer() {
      const { data } = await this.$request({
        url: "/playerinfo/setScore",
        method: "put",
        data: this.addPlayerForm,
      });
      if (data.code === 200) {
        this.addPlayerShow = false;
        return this.$refs.matchToastRef.show({
          title: data.message,
          type: "success",
        });
      } else {
        return this.$refs.matchToastRef.show({
          title: data.message,
          type: "error",
        });
      }
    },

    // 显示删除比赛信息
    showDeleteAllMatches(id) {
      this.deleteMatchShow = true;
      this.matchId = id;
    },

    // 删除比赛信息
    async deleteMatch() {
      const { data } = await this.$request({
        url: `/match/${this.matchId}`,
        method: "delete",
      });
      if (data.code === 200) {
        this.deleteMatchShow = false;
        return uni.reLaunch({
          url: "/pages/match/index",
        });
      } else {
        return this.$refs.matchToastRef.show({
          title: data.message,
          type: "error",
        });
      }
    },

    // 点击加载更多数据
    load() {
      if (this.currentPage >= this.total) return;
      this.status = "loading";
      this.currentPage = ++this.currentPage;
      setTimeout(() => {
        if (this.roleId === 1 || this.roleId === 2) {
          this.getCurrentMatches(this.currentPage, this.size);
        } else {
          this.getAllMatches(this.currentPage, this.size);
        }
        if (this.currentPage >= this.total) this.status = "nomore";
        else this.status = "loadmore";
      }, 2000);
    },
  },

  onLoad() {
    this.roleId = uni.getStorageSync("userInfo").roleid;
    if (this.roleId === 2) {
      this.getCurrentCoach();
    }
    if (this.roleId === 1 || this.roleId === 2) {
      this.getCurrentTeam();
    } else {
      this.getAllMatches(this.currentPage, this.size);
    }
    this.getAllMatches(this.currentPage, this.size);
  },
  onReady() {
    this.getAllTeams();
    this.getAllSpaces();
    this.$refs.addMatchFormRef.setRules(this.addMatchFormRule);
  },
};
</script>

<style scoped lang="scss">
.wrap {
  padding: 30rpx;

  .btn {
    width: 50%;
    margin-top: 15rpx;
    margin-left: auto;
    margin-right: auto;
  }

  .addMatchForm,
  .updateMatchForm {
    padding: 60rpx 30rpx 30rpx 30rpx;
  }

  .remark {
    padding: 15rpx 30rpx;

    text {
      color: #606266;
    }

    view {
      color: #909399;
      margin: 20rpx 0;
    }
  }

  .addResult {
    margin: 35rpx 20rpx 15rpx 20rpx;
  }

  u-popup {
    view {
      padding: 15rpx 30rpx;

      text {
        font-weight: 800;
        font-size: 35rpx;
        margin-bottom: 20rpx;
      }
    }
  }
}


</style>